#include "mainWindow.h"
#include "chessDef.h"
#include "multiGame.h"
#include "singleGame.h"
#include "netGame.h"
#include "playerChoiceDialog.h"
#include "aiDifficultyDialog.h"

#include <QHBoxLayout>
#include <QMessageBox>
#include <QPropertyAnimation>
#include <QShortcut>
#include <QProgressDialog>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow {parent}
{
    // 设置主窗口属性
    setWindowTitle("中国象棋");
    resize(MAIN_WIN_WIDTH, MAIN_WIN_HEIGHT);

    // 创建中央部件和主布局
    centralWidget.reset(new QWidget(this));
    mainLayout.reset(new QHBoxLayout(centralWidget.get()));

    // 创建按钮区域 - 初始状态只显示按钮
    createButtonArea();
    // 初始化返回按钮
    setupBackButton();

    // 创建堆栈窗口 - 初始不显示
    createStackedWidget();

    // 设置初始布局
    mainLayout->addWidget(buttonWidget.get());
    setCentralWidget(centralWidget.get());

    // 连接按钮信号
    connectButtons();
}

void MainWindow::createButtonArea() {
    buttonWidget.reset(new QWidget(this));
    QVBoxLayout *buttonLayout = new QVBoxLayout(buttonWidget.get());
    buttonLayout->setAlignment(Qt::AlignCenter);

    // 创建三个按钮
    multiGameButton.reset(new QPushButton("双人对战", buttonWidget.get()));
    singleGameButton.reset(new QPushButton("人机对战", buttonWidget.get()));
    netGameButton.reset(new QPushButton("匹配对战", buttonWidget.get()));

    // 设置按钮样式和大小
    multiGameButton->setFixedSize(MAIN_BUTTON_WIDTH, MAIN_BUTTON_HEIGHT);
    singleGameButton->setFixedSize(MAIN_BUTTON_WIDTH, MAIN_BUTTON_HEIGHT);
    netGameButton->setFixedSize(MAIN_BUTTON_WIDTH, MAIN_BUTTON_HEIGHT);

    // 添加到布局
    buttonLayout->addStretch(2);
    buttonLayout->addWidget(multiGameButton.get());
    buttonLayout->addSpacing(20);
    buttonLayout->addWidget(singleGameButton.get());
    buttonLayout->addSpacing(20);
    buttonLayout->addWidget(netGameButton.get());
    buttonLayout->addStretch(1);
}

void MainWindow::setupBackButton() {
    QShortcut *backShortcut = new QShortcut(QKeySequence("Esc"), this);
    connect(backShortcut, &QShortcut::activated, this, &MainWindow::showBackConfirm);
    // 创建返回按钮（初始隐藏）
    backButton.reset(new QPushButton("← 返回", this));
    backButton->setFixedSize(BACK_BUTTON_WIDTH, BACK_BUTTON_HEIGHT);
    backButton->move(5, 5);  // 左上角位置
    backButton->hide();  // 初始隐藏

    // 设置按钮样式
    backButton->setStyleSheet(
        "QPushButton {"
        "  background-color: rgba(240,240,240,150);"  // 半透明
        "  border: 1px solid #ccc;"
        "  border-radius: 4px;"
        "  font-size: 14px;"
        "}"
        "QPushButton:hover {"
        "  background-color: rgba(224,224,224,200);"
        "}");
    connect(backButton.get(), &QPushButton::clicked, this, &MainWindow::showBackConfirm);
}

void MainWindow::showBackConfirm() {
    setStyleSheet(R"(
    /* 主对话框样式 - 彩虹渐变背景 */
    QMessageBox {
        background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                                  stop:0 #FF9AA2, stop:0.25 #FFB7B2,
                                  stop:0.5 #FFDAC1, stop:0.75 #E2F0CB,
                                  stop:1 #B5EAD7);
        border-radius: 15px;
        border: 2px solid #FFFFFF;
        font-family: "Microsoft YaHei";
        min-width: 320px;
    }

    /* 标题样式 */
    QMessageBox QLabel#qt_msgbox_label {
        color: #5E2B97;
        font-size: 18px;
        font-weight: bold;
        padding: 15px 20px 5px;
    }

    /* 内容文字样式 */
    QMessageBox QLabel#qt_msgbox_label[text] {
        color: #2D3250;
        font-size: 15px;
        padding: 0 20px 15px;
    }

    /* 按钮容器样式 */
    QMessageBox QDialogButtonBox {
        padding: 0 20px 15px;
    }

    /* 按钮基础样式 */
    QMessageBox QPushButton {
        background: rgba(255,255,255,0.85);
        border: 1px solid rgba(255,255,255,0.9);
        border-radius: 8px;
        color: #5E2B97;
        font-size: 14px;
        min-width: 90px;
        padding: 8px 20px;
        margin: 0 8px;
    }

    /* 按钮悬停效果 */
    QMessageBox QPushButton:hover {
        background: rgba(255,255,255,0.95);
        border-color: #FFFFFF;
        color: #3A1078;
    }

    /* 按钮按下效果 */
    QMessageBox QPushButton:pressed {
        background: rgba(255,255,255,0.7);
    }

    /* 图标区域调整 */
    QMessageBox QLabel#qt_msgboxex_icon_label {
        padding-left: 25px;
    }

    /* 添加内阴影增强层次 */
    QMessageBox QFrame {
        background: transparent;
        border-radius: 15px;
    }
)");
    QMessageBox msgBox(this);
    msgBox.setWindowTitle("返回确认");
    msgBox.setText("确定要返回主菜单吗？");

    // 设置中文按钮
    QPushButton *confirmBtn = msgBox.addButton("确定返回", QMessageBox::YesRole);
    QPushButton *cancelBtn = msgBox.addButton("继续游戏", QMessageBox::NoRole);

    // 设置按钮样式（覆盖全局设置中的特定按钮）
    confirmBtn->setStyleSheet(
        "background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "stop:0 #FF6B6B, stop:1 #FF8E8E);"
        "color: white;"
        "font-weight: bold;"
        );

    cancelBtn->setStyleSheet(
        "background: rgba(255,255,255,0.9);"
        "color: #5E2B97;"
        );

    // 显示对话框
    msgBox.exec();
    if (msgBox.clickedButton() == confirmBtn) {
        returnToMainMenu();
    }

}

void MainWindow::returnToMainMenu() {
    // 清空游戏界面
    clearStackedWidget();

    stackedWidget->hide();
    buttonWidget->show();
    backButton->hide();  // 隐藏返回按钮
}

void MainWindow::createStackedWidget() {
    stackedWidget.reset(new QStackedWidget(this));
    stackedWidget->hide(); // 初始隐藏
}

void MainWindow::connectButtons() {
    // 双人对战按钮
    connect(multiGameButton.get(), &QPushButton::clicked, this, [this]() {
        showGamePage(0);
    });

    // 人机对战按钮
    connect(singleGameButton.get(), &QPushButton::clicked, this, [this]() {
        showGamePage(1);
    });

    // 匹配对战按钮
    connect(netGameButton.get(), &QPushButton::clicked, this, [this]() {
        showGamePage(2);
    });
}

bool MainWindow::popSideDialog() {
    // 显示阵营选择对话框
    PlayerChoiceDialog campDialog(this);

    if (campDialog.exec() == QDialog::Accepted) {
        // 再选择难度
        AIDifficultyDialog difficultyDialog(this);
        if (difficultyDialog.exec() == QDialog::Accepted) {
            // 创建新游戏界面
            singleGame->setPlayerSide(campDialog.selectedSide());
            singleGame->setAIDifficulty(difficultyDialog.selectedDifficulty());
            stackedWidget->addWidget(singleGame.get());
            return true;
        }
    } else {
        returnToMainMenu(); // 直接返回主菜单
    }
    return false;
}

void MainWindow::initGame() {
    netGame.reset(new NetGame());
    multiGame.reset(new MultiGame());
    singleGame.reset(new SingleGame());
}

void MainWindow::showGamePage(int index) {
    // 隐藏按钮区域
    buttonWidget->hide();

    initGame();
    // 创建新界面
    switch(index) {
    case 0: // 双人对战
        // 连接子界面的返回信号
        connect(multiGame.get(), &Board::requestReturnToMainMenu, this, &MainWindow::returnToMainMenu);
        stackedWidget->addWidget(multiGame.get());
        break;
    case 1: // 人机对战
		// 连接子界面的返回信号
		connect(singleGame.get(), &Board::requestReturnToMainMenu, this, &MainWindow::returnToMainMenu);
		// 弹出选择对话框
        if (!popSideDialog()) {
            return;
        }
        break;
    case 2: // 网络对战
        connect(netGame.get(), &Board::requestReturnToMainMenu, this, &MainWindow::returnToMainMenu);
        if (!showFieldExplain()) {
            return;
        }
        executeNetMatch();
        return;
        break;
    }

    setupGameUI();
}

void MainWindow::setupGameUI() {
    // 隐藏按钮区域
    buttonWidget->hide();
    // 显示堆栈窗口并切换到对应页面
    stackedWidget->show();
    stackedWidget->setCurrentIndex(0);

    // 显示返回按钮
    backButton->show();
    backButton->raise();

    // 调整布局
    mainLayout->removeWidget(buttonWidget.get());
    mainLayout->addWidget(stackedWidget.get());
}

void MainWindow::clearStackedWidget() {
    // 删除所有子界面
    while (stackedWidget->count() > 0) {
        stackedWidget->removeWidget(stackedWidget->widget(0));
    }
}

bool MainWindow::showFieldExplain() {
    // 弹出一个说明框, 只有确认按钮
    // 局时: 20分钟
    // 步时: 60秒
    // 局时、步时超时判负(红色字体)
    // Create and style the message box
    QMessageBox netGameInfo(this);
    netGameInfo.setWindowTitle("本场说明");

    // Set the content with HTML formatting for colored text
    netGameInfo.setText(tr("<b>局时:</b> 20分钟<br>"
        "<b>步时:</b> 60秒<br><br>"
        "<span style='color: red;'>局时、步时超时判负</span>"));

    // 添加两个按钮：确认（默认） + 返回主菜单
    QPushButton* confirmButton = netGameInfo.addButton("确认", QMessageBox::AcceptRole);
    QPushButton* returnButton = netGameInfo.addButton("返回主菜单", QMessageBox::RejectRole);

    // Apply the custom style sheet
    netGameInfo.setStyleSheet(R"(
    /* 主对话框样式 - 彩虹渐变背景 */
    QMessageBox {
        background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                                  stop:0 #FF9AA2, stop:0.25 #FFB7B2,
                                  stop:0.5 #FFDAC1, stop:0.75 #E2F0CB,
                                  stop:1 #B5EAD7);
        border-radius: 15px;
        border: 2px solid #FFFFFF;
        font-family: "Microsoft YaHei";
        min-width: 320px;
    }

    /* 标题样式 */
    QMessageBox QLabel#qt_msgbox_label {
        color: #5E2B97;
        font-size: 18px;
        font-weight: bold;
        padding: 15px 20px 5px;
    }

    /* 内容文字样式 */
    QMessageBox QLabel#qt_msgbox_label[text] {
        color: #2D3250;
        font-size: 15px;
        padding: 0 20px 15px;
    }

    /* 按钮容器样式 */
    QMessageBox QDialogButtonBox {
        padding: 0 20px 15px;
    }

    /* 按钮基础样式 */
    QMessageBox QPushButton {
        background: rgba(255,255,255,0.85);
        border: 1px solid rgba(255,255,255,0.9);
        border-radius: 8px;
        color: #5E2B97;
        font-size: 14px;
        min-width: 90px;
        padding: 8px 20px;
        margin: 0 8px;
    }

    /* 按钮悬停效果 */
    QMessageBox QPushButton:hover {
        background: rgba(255,255,255,0.95);
        border-color: #FFFFFF;
        color: #3A1078;
    }

    /* 按钮按下效果 */
    QMessageBox QPushButton:pressed {
        background: rgba(255,255,255,0.7);
    }

    /* 图标区域调整 */
    QMessageBox QLabel#qt_msgboxex_icon_label {
        padding-left: 25px;
    }

    /* 添加内阴影增强层次 */
    QMessageBox QFrame {
        background: transparent;
        border-radius: 15px;
    }
    )");

    // Show the message box
    netGameInfo.exec();

    // 判断用户点击的是哪个按钮
    if (netGameInfo.clickedButton() == returnButton) {
        // 用户点击了"返回主菜单"
        returnToMainMenu();
        return false;          // 直接返回，不进入网络对战
    }
    else {
        return true;
    }
}

void MainWindow::matchSuccessToConfig(QString roomId, QString opponentId, bool otherIsRed) {
    netGame->setRoomIdAndOpponentId(roomId, opponentId);
    netGame->setPlayerSide(otherIsRed);
    stackedWidget->addWidget(netGame.get());
    setupGameUI(); // 设置游戏界面
}

void MainWindow::executeNetMatch() {
    // 创建进度对话框
    QProgressDialog* progressDialog = new QProgressDialog(
        tr("正在匹配对手..."), tr("取消"), 0, 0, this);
    progressDialog->setAttribute(Qt::WA_DeleteOnClose);
    progressDialog->setWindowModality(Qt::WindowModal);

    // 连接信号槽
    connect(netGame.get(), &NetGame::matchFound, progressDialog, 
        [this, progressDialog](QString roomId, QString opponentId, bool otherIsRed) {
        progressDialog->close();
        matchSuccessToConfig(roomId, opponentId, otherIsRed);
        });

    connect(netGame.get(), &NetGame::matchFailed, progressDialog,
        [this, progressDialog](const QString& reason) {
        progressDialog->close();
        netGame->m_socket->disconnectFromHost();
        QMessageBox::warning(progressDialog->parentWidget(), tr("匹配失败"), reason);
        });

    connect(progressDialog, &QProgressDialog::canceled, netGame.get(), [this, progressDialog]() {
        if (netGame->matchResult == MatchResult::MATCH_WAITING) {
            netGame->m_socket->disconnectFromHost();
        }
        returnToMainMenu();
        });

    // 开始匹配
    progressDialog->show();
    netGame->startMatchmaking();
}

